package com.xquant.trade.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.dom4j.xpath.DefaultXPath;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CommonUtils {

    public static List<String> getResultByNodeNameForNameSpace(String xml, String nodeName, String nameSpaceName, String nameSpaceUrl) throws DocumentException {
        Document doc = DocumentHelper.parseText(xml);
        DefaultXPath xPath = new DefaultXPath("//" + nodeName);
        xPath.setNamespaceURIs(Collections.singletonMap(nameSpaceName, nameSpaceUrl));
        List<Node> nodes = xPath.selectNodes(doc);
        List<String> list = new ArrayList<>();
        for (Node node:nodes){
            list.add(node.getText());
        }
        return list;
    }

    public static BigDecimal getAnnualRatio(String calcDate, String begDate, String endDate, String dayCount) {
        long term = DateUtil.betweenDay(DateUtil.parseDate(begDate), DateUtil.parseDate(endDate), true);
        //365F 时需要判断是否闰年
        Integer daycouterDays = 365;
        if (dayCount.contains("F")) {
            daycouterDays = DateUtil.isLeapYear(Integer.parseInt(calcDate.substring(0, 4))) ? 366 : 365;
        } else {
            String regEx = "\\D+";
            daycouterDays = Integer.parseInt(dayCount.replaceAll(regEx, "").trim());
        }
        //天数默认加一天
        return NumberUtil.div(BigDecimal.valueOf(term), daycouterDays, 20);
    }
}
